<?php
namespace app\index\controller;
use app\common\controller\IndexBaseController;
use think\Controller;
use think\Db;
use app\index\model\MemberModel;
use app\index\controller\IndexController;

class MemberController extends IndexBaseController {
		/**
	 * 上传图片
	 */
	public function upload1() {
			$files = $_POST["value"];  
		    $tmp = base64_decode($files);  
		    $fn = time()."_".rand(100000, 999999) . ".jpg";
			$fp = './public/uploads/'. $fn;
			$fp1 = '/public/uploads/'. $fn;
		    $res=file_put_contents( $fp, $tmp);
			if($res){
				return json(["code"=>200,'url'=>$fp1	]);
			}else{
				return json(["code"=>400,'url'=>$fp1	]);
			}
		
		exit;
	}
	public function tixian(){
		$user_info = db('member')->where('id',session('info_user')['id'])->find();
		$config=get_config("site_config");
		if($_POST){
			$cashreg_money=input("cashreg_money");
			if(!$user_info||$cashreg_money>$user_info['money']){
				return json(["code"=>404,'msg'=>'提现失败']);
			}
			Db::startTrans();
			$u_res=db('member')->where('id',session('info_user')['id'])->setDec("money",$cashreg_money);
			if($u_res){
				$data['uid']=session('info_user')['id'];
				$data['money']=$cashreg_money;
				$data['add_time']=now_time();
				$data['fee']=$config['order_fee'];
				$data['rest_money']=$cashreg_money-$cashreg_money*$config['order_fee'];
				$res=db('tixian')->insert($data);
				if($res){
					Db::commit();
					return json(["code"=>200,"msg"=>"申请提现成功"]);
				}else{
					Db::rollback();
					return json(["code"=>401,"msg"=>"提现失败"]);
				}
			}else{
				Db::rollback();
				return json(["code"=>401,"msg"=>"提现失败"]);
			}
		}
		
		$this->assign("user_info",$user_info);
		$this->assign("config",$config);
		return $this->fetch();
	}
	//会员中心首页
	public function index() {
		$Indexcont = new IndexController();
		
		//申购处理
		$Indexcont->compute_subscribe();
		
		$user_info = db('member')->where('id',session('info_user')['id'])->find();
		
		$this->assign("user_info",$user_info);
		
		
		return $this->fetch();
	}

	//申购
	public function subscribe() {
		
		$user_info = db('member')->where('id',session('info_user')['id'])->find();
		
		$this->assign("user_info",$user_info);
		
		//获取认筹的产品
		$goods_list = db('goods')->select();
		
		$this->assign("goods_list",$goods_list);
		
		//申购申请
		if(request()->isPost()){
			$param=input('post.');
			//商品信息
			$goods_infor = db('goods')->where('id',$param['goods_id'])->find();
			//申购总金额
			$total_price =  bcmul($goods_infor['price'], $param['buy_number'], 2);
			
			$result = bccomp($user_info['money'], $total_price, 2);
			if($param['buy_number'] > ($goods_infor['stock']-$goods_infor['residue_stock'])){
				return json(["code"=>408,"msg"=>'认购份额不能大于剩余认购份额']); 
			}
			
			if($result<0){
				return json(["code"=>408,"msg"=>'余额不足请先充值']); 
			}else{
				$sn = order_create_no();
				// 启动事务
				Db::startTrans();
				try{	
						$new_stock 			= $goods_infor['stock'] - $param['buy_number'];
						$new_residue_stock 	= $goods_infor['residue_stock']  + $param['buy_number'];
						
						//扣除剩余数量
						db('goods')->where('id',$param['goods_id'])->update(['stock' => $new_stock,'residue_stock'=>$new_residue_stock]);

						//认筹日志
						$data['user_id'] 		= $user_info['id'];
						$data['goods_id'] 		= $goods_infor['id'];
						$data['goods_price'] 	= $goods_infor['price'];
						$data['goods_name'] 	= $goods_infor['name'];
						$data['buy_number'] 	= $param['buy_number'];
						$data['coupon'] 		= $param['yougou'];
						$data['frozen_money'] 	= $total_price;
						$data['sn'] 			= $sn;
						$data['add_time'] 		= now_time();
						
						$result2 = db('subscribe')->insert($data);
						
						//冻结后余额
						$freeze_yue = bcsub($user_info['money'], $total_price, 2);
						
						//冻结后冻结金额
						$freeze_money = bcadd($user_info['frozen_money'], $total_price, 2);
						//更新用户余额
						$result3 = db('member')->where('id', $user_info['id'])->update(['money' => $freeze_yue,'frozen_money'=>$freeze_money]);
									
						// 提交事务
			    		Db::commit(); 		
						
						if($result2 && $result3){
							return json(["code"=>200,"msg"=>'申购成功']); 
						}else{
							return json(["code"=>402,"msg"=>'申购失败']); 
						}
					} catch (\Exception $e) {
						// 回滚事务
					    Db::rollback();
						//dump($e->getMessage());
						return json(["code"=>405,"msg"=>'数据异常请联系管理员流程号:'.$sn]);
				    
					}	
			}
		}
		//获取我的所有申购
		$subscribe_list = db('subscribe')
							->where('user_id',session('info_user')['id'])
							->where('state',2)
							->paginate(10); 
		
		$this->assign("list",$subscribe_list);
		
		
		
		//获取发行的产品
		$launch_lis = db('goods')->paginate(10); 
		
		$this->assign("launch_list",$launch_lis);
		
		
		return $this->fetch();
	}
	
	//佣金说明
	function vip_flow(){
		return $this->fetch();
	}
	
	//充值
	public function recharge() {
		return $this->fetch();
	}
	//我的钱包
	public function my_wallet() {
		$price=0;//总市值
		$yk=0;//盈亏
		$ky=0;//可用资金
		$list=[];
		if(session('uid')){
			$ky=session('info_user')['money'];
			$where["user_id"]=session('uid');
			$where['nums']=['>',0];
			$list=db("product")->where($where)->select();
			foreach($list as $k=>$p){
				$price  += $p['price']*$p['nums'];//
				$o_w["status"]=2;
				$o_w['goods_id']=$p['goods_id'];
				$dt=db("order")->where($o_w)->field("avg(price) price ")->find();
				if($dt){
					$yk+=$dt['price']-$p['price'];
					$list[$k]['avg']=$dt['price'];//涨跌
					$list[$k]['zd']=$dt['price']-$p['price'];
				}else{
					$list[$k]['avg']=$p['price'];//涨跌
					$list[$k]['zd']=0;
				}
			}
		}
		$user=db('member')->find(session("uid"));
		$this->assign('user',$user);
		$this->assign("ky",$ky);
		$this->assign("price",$price);
		$this->assign("yk",$yk);
		$this->assign("list",$list);
		return $this->fetch();
	}
	//消费记录
	public function wallet_detail() {
		return $this->fetch();
	}
	//我的会员
	public function my_vip() {
		
		//获取当前店铺商品
		$user_list = db('member')
						->field('id,add_time')
						->where('pid',session('info_user')['id'])
						->order('add_time desc')
						->paginate(20);
						
		$this->assign("user_list",$user_list);
		
		return $this->fetch();
	}
	
	//会员详情
	public function member() {
		$user=session("info_user");
		$this->assign("user",$user);
		return $this->fetch();
	}
	//修改会员信息
	public function up_userinfo(){
		$user=session("info_user");
		$res=db('member')->where("id",session("uid"))->update(["real_name"=>input("name"),'thumb'=>input("thumb")]);
		if($res){
			$user['thumb']=input("thumb");
			$user['real_name']=input("name");
			session("info_user",$user);
			return json(["code"=>200,'msg'=>'修改成功']);
		}else{
			return json(["code"=>400,'msg'=>'修改失败']);
		}
	}
	//新增银行卡
	public function add_bankc() {
		
		$user_info = db('member')->where('id',session('info_user')['id'])->find();
		
		if(request()->isPost()){
			$param=input('post.');
			$result = db('member')->where('id', session('info_user')['id'])->update($param);
			if($result){
				$this->success('操作成功');
			}
			$this->error('操作失败');
		}
		
		$this->assign("user_info",$user_info);
		
		
		return $this->fetch();
	}
	//帮助中心
	public function help_list() {
		
		
		return $this->fetch();
	}
	//帮助中心详情
	public function help_show1() {
		return $this->fetch();
	}
	//帮助中心详情
	public function help_show2() {
		return $this->fetch();
	}
	//帮助中心详情
	public function help_show3() {
		return $this->fetch();
	}
	//帮助中心详情
	public function help_show4() {
		return $this->fetch();
	}
	//帮助中心详情
	public function help_show5() {
		return $this->fetch();
	}
	
	//设置安全密码
	function eidt_paypwd(){
		if(request()->isPost()){
			$user_info = db('member')->where('id',session('info_user')['id'])->find();
			
			if(strlen($user_info['pay_password'])>2){
				//检查密码
				if($user_info['pay_password'] != md5_salt($_POST['pay_password'])){
					return json(["code"=>402,"msg"=>"安全密码错误"]);
				}else{
					return json(["code"=>200,"msg"=>"欢迎进入"]);
				}
			}else{
				//新增密码
				db('member')->where('id', session('info_user')['id'])->update(['pay_password' => md5_salt($_POST['pay_password'])]);
				return json(["code"=>200,"msg"=>"设置安全密码成功"]);
			}
		}
	}
	
	
	
	//我的出售
	public function my_market() {
		$where['o.uid']=session("uid");
		$field="o.*,g.name";
		$list=db("order o")->join("goods g"," g.id=o.goods_id")->where($where)->field($field)
		->order("o.add_time asc")->select();
		$this->assign("list",$list);
		return $this->fetch();
	}
	//我的进货
	public function my_stock() {
		$where['o.uid']=session("uid");
		$field="o.*,g.name";
		$list=db("order o")->join("goods g"," g.id=o.goods_id")->where($where)->field($field)
		->order("o.status asc")->select();
		$this->assign("list",$list);
		return $this->fetch();
	}
	//我的申购
	public function my_subscribe() {
		//获取我的所有申购
		$subscribe_list = db('subscribe')->where('user_id',session('info_user')['id'])->paginate(10); 
		$this->assign("list",$subscribe_list);
		
		return $this->fetch();
	}
	
	//邀请好友
	function invitation(){
		
		$code_url="http://".$_SERVER['HTTP_HOST']."/index/index/regist?user_id=".session("uid");
		
		$this->assign("code_url",$code_url);
		
		return $this->fetch();
	}
	
	
	
}
